import { reactive, ref } from "vue";
import { defineStore } from "pinia";
import { playerConfig } from "@/config/static";
import type { CharacterAnimationController } from "@/utils/character";

type baseStats = {
  health: number;
  maxHealth: number;
  mana: number;
  attack: number;
  defense: number;
  speed: number;
  critRate: number;
  critDamage: number;
  accuracy: number;
  evasion: number;
  energy: number;
};

export const useUserStore = defineStore("user", () => {
  const storedPosition = localStorage.getItem("playerPosition");
  const parsedPosition = storedPosition ? JSON.parse(storedPosition) : null;
  // 玩家位置
  const playerPosition = reactive({
    x: parsedPosition?.x || 200,
    y: parsedPosition?.y || 220,
    direction: {
      name: "down",
      value: 0,
    },
    isMoving: false,
    center: {
      x: playerConfig.initX + playerConfig.width / 2,
      y: playerConfig.initY + playerConfig.height / 2,
    },
  });
  // 玩家实例
  const playerInstance = ref<CharacterAnimationController | null>(null);

  // 角色尺寸
  const characterSize = reactive({
    width: 0,
    height: 0,
  });

  // 角色基础属性
  const baseStats = reactive<baseStats>({
    health: 100, // 生命值
    maxHealth: 100, // 最大生命值
    mana: 50, // 魔法值
    attack: 10, // 攻击力
    defense: 5, // 防御力
    speed: 1.0, // 移动速度
    critRate: 0.2, // 暴击率
    critDamage: 2.0, // 暴击伤害
    accuracy: 0.8, // 命中率
    evasion: 0.1, // 闪避率
    energy: 80, // 能量值
  });

  // 角色状态
  const status = reactive({});

  // 角色经验与等级
  const level = reactive({});

  // 货币
  const currency = reactive({});

  // 技能
  const skills = reactive({});

  // 更新玩家位置
  const updatePlayerPosition = (x: number, y: number) => {
    playerPosition.x = x;
    playerPosition.y = y;
    playerPosition.center.x = x + playerConfig.width / 2;
    playerPosition.center.y = y + playerConfig.height / 2;
    localStorage.setItem("playerPosition", JSON.stringify(playerPosition));
  };

  // 更新玩家方向
  const updatePlayerDirection = (direction: {
    name: "up" | "down" | "left" | "right";
    value: number;
  }) => {
    playerPosition.direction = direction;
  };

  // 设置玩家移动状态
  const setPlayerMoving = (isMoving: boolean) => {
    playerPosition.isMoving = isMoving;
  };

  // 设置玩家实例
  const setPlayerInstance = (instance: CharacterAnimationController | null) => {
    playerInstance.value = instance;
  };

  // 获取玩家实例
  const getPlayerInstance = () => playerInstance;

  /**
   * 设置角色尺寸
   * @param width 角色宽度
   * @param height 角色高度
   */
  function setCharacterSize(width: number, height: number) {
    characterSize.width = width;
    characterSize.height = height;
  }

  return {
    baseStats,
    characterSize,
    playerPosition,
    playerInstance,
    setPlayerMoving,
    setCharacterSize,
    setPlayerInstance,
    getPlayerInstance,
    updatePlayerPosition,
    updatePlayerDirection,
  };
});
